package com.fenghongzhang.day016;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MyService extends Service {

    private MediaPlayer mediaPlayer;
    private List<Music> list;
    private int index = 0;

    private boolean isPlay = true;
    private static final String TAG = "MyService";
    //播放模式
    private int playModle = 0;
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //保证只创建一个
        mediaPlayer = new MediaPlayer();
        //数据源
        list = MusicUtil.getMusic(this);

        MyBroadcast myBroadcast = new MyBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.feng.next");
        intentFilter.addAction("com.feng.pre");
        intentFilter.addAction("com.feng.start");
        intentFilter.addAction("com.feng.pause");
        registerReceiver(myBroadcast,intentFilter);
    }

    //上一首
    public void pre() {
        if(--index <= 0){
            index = 0;
        }
        play(index);
    }

    //上一首
    public void next() {
        if(++index > list.size()-1){
            index = 0;
        }
        play(index);
    }

    //设置播放模式
    public void setModle(int i){
        playModle = i;
    }

    //调至指定的播放位置
    public void seek(int progress){
        mediaPlayer.seekTo(progress);
    }

    //中间人
    class Mybinder extends Binder {
//        public void callPlay(int i) {
//            play(i);
//        }
//        public void callPause(){
//            puase();
//        }
//        public void callRestart(){
//            restart();
//        }
        public MyService getService(){
            return MyService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notify_layout);
        builder.setCustomContentView(remoteViews);
        startForeground(1,builder.build());
        return super.onStartCommand(intent, flags, startId);
    }

    //绑定后,会自动调用,返回代理人对象
    @Override
    public IBinder onBind(Intent intent) {
       return new Mybinder();
    }

    //得到当前播放的最大值
    public int getMax(){
        return mediaPlayer.getDuration();
    }

    //当前进度值
    public int getCurrent(){
        return mediaPlayer.getCurrentPosition();
    }

    //接收一个从页面中点击事件创来的下标,可以播放.
    public void play(int position) {
        sendNotify(position);
        //缓存下标,用来上下首的.
        index = position;
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(list.get(position).getData());
            mediaPlayer.prepareAsync();
            //异步加载完毕监听
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            //播放完成监听
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //自动调用
                    switch (playModle){
                        case MusicUtil.RANDOM:
                            index = new Random().nextInt(list.size());
                            play(index);
                            break;
                        case MusicUtil.ORDER:
//                            next();
                            break;
                        case MusicUtil.SINGE:
                            play(index);
                            break;
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendNotify(int position) {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notify_layout);
        remoteViews.setTextViewText(R.id.notify_title,list.get(position).getTitle());
        remoteViews.setImageViewBitmap(R.id.notify_img, BitmapFactory.decodeFile(list.get(position).getAlbumId()));


        if (isPlay){
            Intent intent2 = new Intent();
            intent2.setAction("com.feng.pause");
            PendingIntent broadcast2 = PendingIntent.getBroadcast(this, 0, intent2, 0);
            remoteViews.setOnClickPendingIntent(R.id.notify_play,broadcast2);
            remoteViews.setImageViewResource(R.id.notify_play,R.mipmap.playbar_btn_pause);
            isPlay = false;
        }else{
            //播放
            Intent intent2 = new Intent();
            intent2.setAction("com.feng.start");
            PendingIntent broadcast2 = PendingIntent.getBroadcast(this, 0, intent2, 0);
            remoteViews.setOnClickPendingIntent(R.id.notify_play,broadcast2);
            remoteViews.setImageViewResource(R.id.notify_play,R.mipmap.playbar_btn_play);
            isPlay = true;
        }
        //点击按钮发送广播
        Intent intent = new Intent();
        intent.setAction("com.feng.next");
        PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, intent, 0);
        remoteViews.setOnClickPendingIntent(R.id.notify_next,broadcast);

        Intent intent1 = new Intent();
        intent1.setAction("com.feng.pre");
        PendingIntent broadcast1 = PendingIntent.getBroadcast(this, 0, intent1, 0);
        remoteViews.setOnClickPendingIntent(R.id.notify_pre,broadcast1);

        builder.setCustomContentView(remoteViews);
        startForeground(1,builder.build());
    }

    public void puase(){
        sendNotify(index);
        mediaPlayer.pause();
    }

    public void restart(){
        sendNotify(index);
        mediaPlayer.start();
    }

    class MyBroadcast extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "onReceive: ");
            String action = intent.getAction();
            if(action.equals("com.feng.next")){
                next();
            }else if(action.equals("com.feng.pre")){
                pre();
            }else if(action.equals("com.feng.start")){
                restart();
            }else if(action.equals("com.feng.pause")){
                puase();
            }

        }
    }
}